package cn.tjjcy.service.process;

import cn.tjjcy.common.DmMsg;
import cn.tjjcy.common.GzResult;
import cn.tjjcy.domain.RealGzConfEntity;
import cn.tjjcy.service.YwscGzLogService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class DefaultProcessService extends AbstractProcessService {

    @Autowired
    private YwscGzLogService ywscGzLogService;


    @Override
    public GzResult gzJudge(DmMsg dmMsg, RealGzConfEntity realGzConfEntity) {
        try {
            String gzParam = realGzConfEntity.getGzParam();
            String gzSql = realGzConfEntity.getGzSql();
            String[] params = gzParam.split(",");
            String opType = dmMsg.getOp_type();
            String table = dmMsg.getTable();
            String sourceTableName = table.split("\\.")[1];
            JSONObject after = dmMsg.getAfter();
            JSONObject before = dmMsg.getBefore();
            if ("I".equalsIgnoreCase(opType)) {
                for (String param : params) {
                    String p = after.getString(param);
                    if (StringUtils.isEmpty(p)) {
                        log.info("【插入操作】规则:[{}]param[{}] 参数为空，不触发规则 返回", realGzConfEntity.getId(),param);
                        return null;
                    }
                }
                for (String param : params) {
                    gzSql = gzSql.replace("#" + param, after.getString(param));
                }

            } else if ("U".equalsIgnoreCase(opType)) {
                for (String param : params) {
                    String p = before.getString(param);
                    if (StringUtils.isEmpty(p)) {
                        log.info("【更新操作】 规则:[{}] param[{}] 参数为空，不触发规则 返回", realGzConfEntity.getId(), param);
                        return null;
                    }
                }
                for (String param : params) {
                    gzSql = gzSql.replace("#" + param, before.getString(param));
                }
            }
            //执行规则
            List<Map<String, Object>> results = SqlRunner.db().selectList(gzSql);
            if (CollectionUtils.isEmpty(results)||results.size()>1) {
                log.info("【规则[{}]】:SQL:[{}] 规则条数不满足，没有触发规则", realGzConfEntity.getId(),gzSql);
                return GzResult.judgeFail("【规则[" + realGzConfEntity.getId() + "]】规则条数["+results.size()+"]不满足，没有触发规则",gzSql);
            }
            log.info("【规则[{}]】 表:[{}] SQL:[{}] 触发通用规则",
                    realGzConfEntity.getId(), sourceTableName, gzSql);
            return  GzResult.judgeSuccess(results.get(0),gzSql);
        } catch (Exception e) {
            log.error("【默认规则[{}]】处理异常",realGzConfEntity.getId(),JSON.toJSON(dmMsg),e);
            return null;
        }
    }

    @Override
    public void gzResult(GzResult judgeResult, DmMsg dmMsg, RealGzConfEntity realGzConfEntity) {
        try {
            String sourceTableName = dmMsg.getTable().split("\\.")[1];
            String resultSql = realGzConfEntity.getResultSql();
            String bmsah=judgeResult.getBmsah();
            resultSql = resultSql.replace("#BMSAH",bmsah).replace("#bmsah",bmsah).replace("#gzid",realGzConfEntity.getGzId());
            boolean result = SqlRunner.db().insert(resultSql);
            log.info("【规则[{}]】 [{}] 表:[{}] 结果:[{}] ", realGzConfEntity.getId(), bmsah, sourceTableName, result);
            judgeResult.setResult(result);
            judgeResult.setResultSql(resultSql);
        } catch (Exception e) {
            log.error("【默认规则[{}]】执行结果异常",realGzConfEntity.getId(),JSON.toJSON(dmMsg),e);
        }
    }


}
